package com.blb.thread;


import java.util.Date;
import java.util.concurrent.*;

public class ThreadPoolDemo {

    /**
     * 测试缓存线程池
     */
    private static void testCachedThreadPool(){
        //工具类创建线程池
        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10000; i++) {
            final int num = i;
            //线程池启动线程执行任务
            pool.execute(() -> {
                System.out.println(Thread.currentThread().getName()+"执行了"+num);
            });
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //关闭线程池
        pool.shutdown();
    }

    /**
     * 测试长度固定的线程池
     */
    private static void testFixedThreadPool(){
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10000; i++) {
            final int n = i;
            pool.execute(() -> {
                System.out.println(Thread.currentThread().getName()+"执行了"+n);
            });
        }
        pool.shutdown();
    }

    /**
     * 测试单个线程的线程池
     */
    private static void testSingleThreadPool(){
        ExecutorService pool = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10000; i++) {
            final int n = i;
            pool.execute(() -> {
                System.out.println(Thread.currentThread().getName()+"执行了"+n);
            });
        }
        pool.shutdown();
    }

    /**
     * 测试可以调度的线程池
     */
    private static void testScheduledThreadPool(){
        //创建可调度线程池
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(10);
        //带延迟执行任务
//        pool.schedule(() -> {
//            System.out.println("Hello,我延迟5s执行");
//        }, 5, TimeUnit.SECONDS);
        //带固定周期执行任务
//        pool.scheduleWithFixedDelay(() -> {
//            System.out.println("Hello，现在时间：" + new Date());
//        },5,1,TimeUnit.SECONDS);
        pool.scheduleAtFixedRate(() -> {
            System.out.println("Hello，现在时间：" + new Date());
        },5,1,TimeUnit.SECONDS);
//        pool.shutdown();
    }

    /**
     * 测试手动创建线程池
     */
    private static void testMyThreadPool(){
        //获得cpu核心数
        int cpuNum = Runtime.getRuntime().availableProcessors();
        int corePoolSize = cpuNum * 2;
        int maxPoolSize = corePoolSize;
        //创建线程池
        ExecutorService pool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        for (int i = 0; i < 10; i++) {
            final int n = i;
            pool.execute(() -> {
                System.out.println(Thread.currentThread().getName()+"执行" + n);
            });
        }
        pool.shutdown();
    }

    public static void main(String[] args) {
//        testCachedThreadPool();
//        testFixedThreadPool();
//        testSingleThreadPool();
//        testScheduledThreadPool();
        testMyThreadPool();
    }
}
